#!/usr/bin/env python

from __future__ import print_function
import sys
import json
try:
    from urllib.parse import urlencode
except ImportError:
    from urllib import urlencode
try:
    import httplib
except ImportError:
    import http.client as httplib

server_host = '127.0.0.1'   # modify this
server_port = 80            # modify this 

def submit(team_token, flag, host=server_host, port=server_port, timeout=5):
    if not team_token or not flag:
        raise Exception('team token or flag not found')
    conn = httplib.HTTPConnection(host, port, timeout=timeout)
    params = urlencode({
        'token': team_token,
        'flag': flag,
    })
    headers = {
        "Content-type": "application/x-www-form-urlencoded"
    }
    conn.request('POST', '/api/flag/submit', params, headers)
    response = conn.getresponse()

    data = response.read()

    conn.close()

    return json.loads(data)

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print('usage: python ./submit_flag.py $team_token $flag')
        sys.exit()
    host = server_host
    if len(sys.argv) > 3:
        host = sys.argv[3]
    print(json.dumps(submit(sys.argv[1], sys.argv[2], host=host), indent=4))
